using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ParallaxBackGround : MonoBehaviour
{

    private Transform cameraTransform;
    private Vector3 lastCameraPos;
    //序列化，可以使private属性在面板中看到并赋值
    [SerializeField] private Vector2 parallaxEffectMultiplier;  //背景移动系数
    private float textureUnitSizeX;
    
    void Start()
    {
        cameraTransform = Camera.main.transform;
        lastCameraPos = cameraTransform.position;
        
        //背景无限滚动相关
        // Sprite sprite = GetComponent<SpriteRenderer>().sprite;
        // Texture2D texture2D = sprite.texture;
        // textureUnitSizeX = texture2D.width / sprite.pixelsPerUnit;
    }

    void Update()
    {
        //视差相关
        Vector3 deltaMovement = cameraTransform.position - lastCameraPos;
        transform.position += new Vector3(this.parallaxEffectMultiplier.x * deltaMovement.x,
                                            this.parallaxEffectMultiplier.y * deltaMovement.y);
        lastCameraPos = cameraTransform.position;
        
        //背景无限滚动相关(目前存在bug，背景向前移动不是完美衔接)
        // if (Mathf.Abs(cameraTransform.position.x - transform.position.x) >= textureUnitSizeX)
        // {
        //     float offsetPositionX = (cameraTransform.position.x - transform.position.x) % textureUnitSizeX;
        //     transform.position = new Vector3(cameraTransform.position.x + offsetPositionX, transform.position.y);
        // }
    }
}
